<?php

namespace SunAdmin\Service\FileSystem;

use SunAdmin\Model\AttachmentModel;

class Delete extends FilesystemBase
{
    /**
     * 通过附件ID删除文件
     */
    public function deleteById(int $attachmentId): array
    {
        try {
            $attachment = AttachmentModel::find($attachmentId);
            if (!$attachment) {
                throw new \Exception("附件记录不存在");
            }

            // 如果磁盘不匹配，重新初始化
            if ($attachment->disk !== $this->currentDisk) {
                $this->initFilesystem($attachment->disk);
            }

            // 删除物理文件
            $deleted = $this->filesystem->delete($attachment->path);
            
            if ($deleted) {
                $attachment->delete();
                return [
                    'status' => true,
                    'message' => '文件删除成功',
                    'data' => ['id' => $attachmentId]
                ];
            } else {
                throw new \Exception("物理文件删除失败");
            }
        } catch (\Exception $e) {
            \think\facade\Log::error('文件删除失败: ' . $e->getMessage());
            return [
                'status' => false,
                'message' => '文件删除失败: ' . $e->getMessage(),
                'data' => []
            ];
        }
    }

    /**
     * 通过文件路径删除文件
     */
    public function deleteByPath(string $filePath): array
    {
        try {
            $deleted = $this->filesystem->delete($filePath);
            
            if ($deleted) {
                // 同时删除数据库记录
                AttachmentModel::where('path', $filePath)
                    ->where('disk', $this->currentDisk)
                    ->delete();
                
                return [
                    'status' => true,
                    'message' => '文件删除成功',
                    'data' => ['path' => $filePath]
                ];
            } else {
                throw new \Exception("文件删除失败");
            }
        } catch (\Exception $e) {
            return [
                'status' => false,
                'message' => '文件删除失败: ' . $e->getMessage(),
                'data' => []
            ];
        }
    }

    /**
     * 批量删除文件
     */
    public function batchDelete(array $attachmentIds): array
    {
        $results = [];
        $successCount = 0;

        foreach ($attachmentIds as $id) {
            $result = $this->deleteById($id);
            $results[] = $result;
            
            if ($result['status']) {
                $successCount++;
            }
        }

        return [
            'status' => $successCount === count($attachmentIds),
            'data' => $results,
            'message' => "批量删除完成，成功 {$successCount} 个"
        ];
    }
} 